package com.luyuan.crm.member.service.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.luyuan.crm.member.model.MemberGroup;
import com.luyuan.crm.member.service.MemberGroupService;
import com.ruijie.foundation.dao.extend.support.HibernateEntityExtendDao;
import com.ruijie.foundation.query.Page;
import com.ruijie.foundation.query.criteria.CriteriaQueryTemplate;
import com.ruijie.foundation.query.criteria.CriteriaTemplate;

public class MemberGroupServiceImpl extends HibernateEntityExtendDao<MemberGroup> implements MemberGroupService {

    @Override
    public MemberGroup getById(String id) {
        return safeGet(id);
    }

    @Override
    public void addMemberGroup(MemberGroup memberGroup) {
        save(memberGroup);
    }

    @Override
    public void removeMemberGroup(final MemberGroup memberGroup) {
        getHibernateTemplate().execute(new HibernateCallback() {
            @Override
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                SQLQuery query = session.createSQLQuery("delete from lyt_member_group_relation where member_group_id = ?");
                query.setParameter(0, memberGroup.getId());
                return query.executeUpdate();
            }
        });

        remove(memberGroup);
    }

    @Override
    public void updateMemberGroup(MemberGroup memberGroup) {
        evit(memberGroup);
        getHibernateTemplate().merge(memberGroup);
    }

    @Override
    public Page pagedQuery(CriteriaTemplate criteria, int pageNo, int pageSize, List<Order> orders) {
        CriteriaQueryTemplate qt = new CriteriaQueryTemplate(getSessionFactory());
        return qt.pagedQuery(criteria, pageNo, pageSize, orders);
    }

}
